package org.gzc.stack;

/**
 * @Description: 链表实现栈
 * @Author: guozongchao
 * @Date: 2020/8/4 10:15
 */
public class LinkListStack<T> {
    private Node head;
    private int top =-1;
    private int maxSize;

    public LinkListStack(int maxSize) {
        this.maxSize=maxSize;
        this.head = new Node(null);
    }

    //返回栈元素数量
    public int size() {
        return top+1;
    }

    private boolean isEmpty() {
        return top==-1;
    }

    private boolean isFull() {
        return top+1==maxSize;
    }

    //检查元素是否为空
    private void checkNotNull(T item) {
        if (item == null) {
            throw new NullPointerException("圧入元素不能为空");
        }
    }

    //压栈
    public void push(T item) {
        checkNotNull(item);
        if (isFull()) {
            throw new RuntimeException("栈已经满了");
        }
        Node<T> node = new Node<>(item);
        Node temp=head;
        while (temp.next != null) {
            temp=temp.next;
        }
        temp.next=node;
        top++;
    }

    //出栈
    public T pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        Node temp=head.next;
        head.next = head.next.next;
        top--;
        return (T) temp.item;
    }

    //遍历
    public void display() {
        Node temp=head;
        while (temp.next != null) {
            temp=temp.next;
            System.out.print(temp.item+"---->");
        }
        System.out.println();
    }
    
    class Node<T> {
        public T item;
        public Node next;

        public Node(T item) {
            this.item=item;
        }
    }


    public static void main(String[] args) {
        LinkListStack stack = new LinkListStack(5);

        //入栈
        stack.push("aaa");
        stack.push("bbb");
        stack.push("ccc");
        stack.push("ddd");
        stack.push("eee");

        //显示
        System.out.println("初始数据：");
        stack.display();

        System.out.println("\n再添加一个元素fff：");
        //在添加一个
        try {
            stack.push("fff");
        } catch (RuntimeException e) {
            System.out.println(e.getMessage());
        }


        System.out.println("\n弹出3个元素：");
        //出栈
        for (int i = 1; i <= 3; i++) {
            String item = (String) stack.pop();
            System.out.println("弹出的第"+i+"个元素为："+item);
        }

        System.out.println("\n再入栈元素fff：");
        //再入栈
        stack.push("fff");
        stack.display();

        System.out.print("\n获取当前栈元素个数："+stack.size());
    }
}
